//
//  UIWindow+Lc.m
//  18Birdies
//
//  Created by weihua on 2016/12/26.
//  Copyright © 2016年 Lc. All rights reserved.
//

#import "UIWindow+Lc.h"

@implementation UIWindow (Lc)

- (void)changeRootViewController:(UIViewController*)toRootViewController
                         animate:(ChangeRootAnimate)animate
                      completion:(void (^)(void))completion {
  [self endEditing:YES];
  UIViewController* oldRootViewController = self.rootViewController;
  if (oldRootViewController == nil) {
    self.rootViewController = toRootViewController;
    if (completion != nil) {
      completion();
    }
    return;
  }
  if (oldRootViewController.presentedViewController != nil) {
    // fix memory leak
    [oldRootViewController dismissViewControllerAnimated:NO completion:nil];
  }

  typedef void (^Animation)(void);
  Animation animation = ^{
    BOOL oldState = [UIView areAnimationsEnabled];
    [UIView setAnimationsEnabled:NO];
    self.rootViewController = toRootViewController;
    [UIView setAnimationsEnabled:oldState];
  };
  if (animate == ChangeRootAnimatePresent) {
    [UIView transitionWithView:self
                      duration:0.5f
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:animation
                    completion:^(BOOL finished) {
                      [oldRootViewController.view removeFromSuperview];
                      if (completion != nil) {
                        completion();
                      }
                    }];
  } else {
    [UIView transitionWithView:self
                      duration:0.5f
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:animation
                    completion:^(BOOL finished) {
                      [oldRootViewController.view removeFromSuperview];
                      if (completion != nil) {
                        completion();
                      }
                    }];
  }
}

@end
